<?php

namespace app\model;

use think\Model;
use think\Db;
use app\model\Channel;
use app\model\Mch;
class Order extends Model{
    

    /**
     * Undocumented 创建订单
     *
     * @param [type] $data
     * @return void
     */
    public static function orderAdd($data,$item){
       
        $amount = abs($data['amount']/100);
        $p = Channel::get_payment($item['patment_id']);
        $total_cost = abs($amount*$p['cost']);//成本
        $total_fee = abs($amount*$item['run_rate']);//商户手续费
        $agent_rate = Mch::getAgentRate($data['mch_id']);//获取代理费率
        $agent_fee = $amount*$agent_rate;//代理手续费
        $agent_amount = 0;
        //未设置代理费率
        if(!empty($agent_fee)){
            $agent_amount = abs($total_fee-$agent_fee);//代理结算
        }
        Db::startTrans();
        try { 
            $order = Order::create([
                "mch_id"           => $data['mch_id'],//商户号
                "out_trade_no"     => $data['out_trade_no'],//商户单号
                "systen_no"        =>getOrderId(),//系统单号
                "amount"           => $amount,//下单金额
                "cost_rate"        => $p['cost'],//成本费率
                "run_rate"         => $item['run_rate'],//运营费率
                "total_fee"        => $total_fee,//商户手续费
                "goods"            => trim($data['goods']),
                "settle"           => $amount-$total_fee,//商户结算金额
                "agent_rate"       => $agent_rate,//代理商费率
                "upstream_settle"  => $amount-$total_cost,//上游结算
                "agent_amount"     => $agent_amount,//代理收益
                "channel_id"       => $p['channel_id'],//渠道id
                "payment_id"       => $item['patment_id'],//支付类型id
                "pay_code"         => $data['service_type'],//支付编码
                "callback_url"     => $data['callback_url'],//异步
                "return_url"       => $data['return_url'],//同步
                "Platform"         => $total_fee-$total_cost-$agent_amount,//平台收益
                "ip"               => get_client_ip(),
                "create_time"      => date('Y-m-d H:i:s',time())
            ]);
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $e->getMessage();
        }
        return ['out_trade_no'=>$order->out_trade_no,'system_sn'=>$order->systen_no];
    }
    /**
     * Undocumented 获取一条订单信息
     *
     * @param [type] $where
     * @return void
     */
    public static function mch_order($where,$field = ''){

        return Order::where($where)->field($field)->find();
    }
    /**
     * Undocumented 更新订单
     *
     * @param [type] $info 订单信息
     * @param [type] $actual_amount 实际支付金额
     * @param [type] $type
     * @param string $transaction_no 三方单号
     * @return void
     */
    public static function order_update($id,$actual_amount,$type,$transaction_no = ''){
        $info = Order::where("id",$id)->lock(true)->find();
        $ramk = $type == 5 ? '商户支付' : '强制入账';
        //获取商户信息
        $mch = Mch::get_mch($info->mch_id);
       
        if($mch->status == 2){
            return ['code'=>0,'out_trade_no'=>$info->systen_no,'msg'=>'商户已禁用'];
        }
        //商户入金状态
        if($mch->rukuan == 2){
            return ['code'=>0,'out_trade_no'=>$info->systen_no,'msg'=>'商户已禁止入金'];
        }
        //支付状态判断
        if($info->pay_status != 1){
            return ['code'=>0,'out_trade_no'=>$info->systen_no,'msg'=>'订单状态不正确'];
        }
        //金额判断
        if(abs($info->amount) - abs($actual_amount) > 1){
            return ['code'=>0,'out_trade_no'=>$info->systen_no,'msg'=>'下单金额和实际支付金额不一致'];
        }
        //支付时间
        $time = date("Y-m-d H:i:s",time());
        Db::startTrans();
        try{ 
            //更新订单
            Order::where("id",$info->id)->update(array(
                "pay_status"     => 2, //支付状态 1、未支付 2、已支付 3、已关闭
                "actual_amount"  => $actual_amount, //实际支付
                "transaction_no" => $transaction_no,//三方流水号
                "pay_time"       => $time, //支付时间
            ));
            //更新商户余额
            Mch::where("mch",$mch->mch)->setInc("balance",$info->settle);
            //插入支付记录
            mchRecord($mch->mch,$ramk,$info->settle,$type,$info->systen_no);
            //更新代理余额
            if(!empty($mch->agent_id)){
                //代理商入金状态
                if(Mch::where("id",$mch->agent_id)->value('rukuan') == 1){
                    Mch::where("id",$mch->agent_id)->setInc('balance',$info->agent_amount);
                    //插入代理记录
                    mchAgentRecord(Mch::get_mch_m($mch->agent_id),'代理收益',$info->agent_amount,$type,$info->systen_no);
                } 
            }
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return array("code"=>0,"out_trade_no"=>$info->systen_no,"msg"=>$e->getMessage());
        }
        //回调数据
        $native = [
            "mch_id" => $info->mch_id,//商户号
            "out_trade_no" => $info->out_trade_no,//商户单号
            "systen_no" => $info->systen_no,//系统单号
            "amount" => $info->amount, //下单金额
            "actual_amount" => $actual_amount,//实际支付
            "pay_time" => strtotime($time),//支付时间
        ];
        //签名
        $native['sign'] = get_sign($native,$mch->md5key);
        //发送异步回调给下游
        $result = self::get_notify($native,$info->callback_url);
        if($result == 'success'){
            $info->notice = 2;
            $info->save();
        }else{
            get_log(['out_trade_no'=>$info->out_trade_no,'result'=>$result,'time'=>date('Y-m-d H:i:s',time())],'callback_abnormal');
        }
        return ['code'=>1,"out_trade_no"=>$info->systen_no,'msg'=>$result];
    }
    /**
     * Undocumented 补发通知
     *
     * @param [type] $native
     * @param [type] $url
     * @return void
     */
    public static function get_notify($native,$url){
       
        $res = curl_json($url,$native);
        return $res;
    }




}
?>